package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.config.AilPayConfig;
import cn.itsource.ymcc.domain.PayFlow;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.mapper.PayFlowMapper;
import cn.itsource.ymcc.mapper.PayOrderMapper;
import cn.itsource.ymcc.producer.PayProducer;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.IPayOrderService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.vo.PayVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Case;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zongchangjiang
 * @since 2023-08-06
 */
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    /**
     * 交易创建，等待买家付款。
     */
    private static final String WAIT_BUYER_PAY = "WAIT_BUYER_PAY";
    /**
     * 未付款交易超时关闭，或支付完成后全额退款。
     */
    private static final String TRADE_CLOSED = "TRADE_CLOSED";
    /**
     * 交易支付成功。
     */
    private static final String TRADE_SUCCESS = "TRADE_SUCCESS";
    /**
     *
     * 交易结束，不可退款。
     */
    private static final String TRADE_FINISHED = "TRADE_FINISHED";

    @Autowired
    private AilPayConfig ailPayConfig;
    @Autowired
    private PayFlowMapper payFlowMapper;
    @Autowired
    private PayProducer payProducer;
    /**
     * 支付流程
     * @param payVo
     * @return
     */
    @Override
    public JsonResult apply(PayVo payVo) {
        PayOrder order_no = baseMapper.selectOne(new QueryWrapper<PayOrder>().eq("order_no", payVo.getOrderNo()));
        AssertUtil.isTrue(order_no!=null,"支付单未生成");
        String subject = order_no.getSubject();
        String page = ailPayConfig.toPay(subject, payVo.getOrderNo(), order_no.getAmount().toString(), payVo.getCallUrl());
        return JsonResult.success().setData(page);
    }

    @Override
    @Transactional
    public void callbackHandle(Map<String, String> parmeter) {
        //修改支付单状态
        editPayOrder(parmeter);
        //添加流水
        addPayFlow(parmeter);
        // MQ 发送消息  去修改订单
        Map<String,Object> map = new HashMap<>();
        map.put("orderNo",parmeter.get("out_trade_no"));
        map.put("orderStatus",getPayStatus(parmeter));
        payProducer.sendEditOrder(map);
        // MQ 发送消息  去添加购买记录

        PayOrder payOrder = baseMapper.selectOne(new QueryWrapper<PayOrder>().eq("order_no", parmeter.get("out_trade_no")));
        map.clear();
        map.put("userId",payOrder.getUserId());
        map.put("courses",payOrder.getRelationId());
        map.put("orderNo",parmeter.get("out_trade_no"));
        payProducer.sendAddUserLearn(map);
    }

    /**
     * 添加流水
     * @param parmeter
     */
    private void addPayFlow(Map<String, String> parmeter) {
        PayFlow payFlow = new PayFlow();
        payFlow.setNotifyTime(new Date());
        payFlow.setSubject(parmeter.get("subject"));
        payFlow.setOutTradeNo(parmeter.get("out_trade_no"));
        payFlow.setTotalAmount(new BigDecimal(parmeter.get("total_amount")));
        payFlow.setTradeStatus(parmeter.get("trade_status"));
        int payStatus = getPayStatus(parmeter);
        payFlow.setPaySuccess(payStatus);
        payFlow.setResultDesc("支付成功");
        payFlowMapper.insert(payFlow);
    }

    /**
     * 修改支付单状态
     * 支付状态：0下单成功待支付，1已支付，2取消支付，3订单退款，4支付超时或失败，5订单确认订单完成
     * @param parmeter
     */
    private void editPayOrder(Map<String, String> parmeter) {
        int item = getPayStatus(parmeter);
        //需要查询支付单出来
        String sn = parmeter.get("out_trade_no");//得到自己的订单号
        PayOrder payOrder = new PayOrder();
        payOrder.setPayStatus(item);
        payOrder.setUpdateTime(new Date());
        baseMapper.update(payOrder,new QueryWrapper<PayOrder>().eq("order_no", sn));
    }

    private int getPayStatus(Map<String, String> parmeter) {
        String status = parmeter.get("trade_status");
        int item = 0;
        switch (status){
            case WAIT_BUYER_PAY: item = 0;break;
            case TRADE_CLOSED: item = 3;break;
            case TRADE_SUCCESS: item = 1;break;
            case TRADE_FINISHED: item = 5;break;
            default: item = 0;
        }
        return item;
    }
}
